﻿function submitComplaint() {
}

var constants = {
    projectToolTip: '楼盘名称',
    moreFunctionExpand: '展开更多找房条件',
    moreFunctionCollapsed: '回到基本找房条件'
}

$(function () {
    initFirstPage();
    initDefaultText();
    initProjectAutoMatch();
    initChangeCity();
});

function initFirstPage() {
    if (typeof (searchCondition) != "undefined")
        initSearchCondition();
    initColspanFun();
    initFavBtn();
    // 发布房源选择区域
    $("#districtSelect").bind("change", function () {
        selectDistrict();
    });
    selectDistrict();
    initAdvertisementImage();
}

// 初始化广告位点击
function initAdvertisementImage() {
   /* $("a.advLink").click(function () {
        DoPost('/Advertisement/Click/' + $(this).attr("advId"));
    });*/

}

// 初始化搜索引擎
function initSearchCondition() {

    // 绑定点击事件
    $("#searchCondition div.searchCondition a").bind("click", function () {
        // change style

        $(this).parents(".searchCondition").find(".noDistrict").removeClass("fco").removeClass("fwb").addClass("fcbl");
        $(this).parents(".searchCondition").find("a").removeClass("fco").removeClass("fwb");
        $(this).addClass("fco").addClass("fwb");
        var field = $(this).parents(".searchCondition").attr("field");
        var data = $(this).attr("data");
        // set data
        if (field != "district") {
            searchCondition[field] = data;
            renewCurrentSearchCondition();
            doSearch();
        }
        return false;
    });

    // 装修条件
    $("#fitment a").bind("click", function () {
        if ($(this).hasClass("fcbl")) {
            $(this).addClass("fco").addClass("fwb").removeClass("fcbl");
            $("#fitment input[type=checkbox]").attr("checked", "");
            $("#fitment label").removeClass("fco").removeClass("fwb");
            calculateFitmentTypeCondition();
            renewCurrentSearchCondition();
            doSearch();
        }
        return false;
    });
    $("#fitment input[type=checkbox]").bind("change", function () {
        var label = $("#fitment label[for=" + $(this).attr("id") + "]");
        if (this.checked) {
            label.addClass("fco").addClass("fwb");
        }
        else {
            label.removeClass("fco").removeClass("fwb");
        }

        // 当所有至少一个装修条件选中时：
        $("#fitment a").addClass("fco").addClass("fwb");
        $("#fitment input[type=checkbox]").each(function () {
            if (this.checked)
                $("#fitment a").removeClass("fco").removeClass("fwb").addClass("fcbl");
        });
        calculateFitmentTypeCondition();
        renewCurrentSearchCondition();
        doSearch();
    });

    // 房源搜索引擎选择区域
    $("#district a").bind("click", function () {
        var district = $(this).attr("data");
        if (!district)
            district = 0;
        if (searchCondition.district != district) {
            searchCondition.district = district;
            searchCondition.districtName = $(this).text();
            searchCondition.zone = '';
            searchCondition.zoneName = '';
            //            $("#zone input[type=checkbox]").attr("checked", "");
            //            if (searchCondition.district > 0) {
            //                $("#zone").show(300);
            //                $("#zone li").hide(100);
            //                $("#zone li[district=" + district + "]").show(300);
            //            }
            //            else {
            //                searchCondition.zone = '';
            //                $("#zone").hide(100);
            //            }
            searchCondition.project = ''; //清除楼盘值
            renewCurrentSearchCondition();
            doSearch();
        }
        return false;
    });


    $("#zone input[type=checkbox]").change(function () {
        var label = $("#zone label[for=" + $(this).attr("id") + "]");
        if (this.checked) {
            label.addClass("fco").addClass("fwb");
        }
        else {
            label.removeClass("fco").removeClass("fwb");
        }
        searchCondition.project = ''; //清除楼盘值
        calculateLocationCondition();
        renewCurrentSearchCondition();
        doSearch();
    });

    // 绑定已选数据
    bindSearchCondition();
    renewCurrentSearchCondition();

    // 确定按钮
    $("#searchCondition input.submitBtn").bind("click", function () {
        fixNumber(this);
        // 位置
        if ($(this).attr('field') == "location") {
            calculateLocationCondition();
        }
        // 装修
        else if ($(this).attr('field') == 'fitmentType') {
            calculateFitmentTypeCondition();
        }
        // 其他
        else {
            calculateCommonCondition(this);
        }
        renewCurrentSearchCondition();
        doSearch();
    });
    // 发布类型Tab
    initPublishTypeTab();

    // 排序链接
    $("a.OrderLink").click(function () {
        if (!$(this).hasClass("orderLinkSelected")) {
            searchCondition.order = $(this).attr("data");
            searchCondition.isAsc = false;
        }
        else {
            if (!searchCondition.isAsc) {
                searchCondition.isAsc = true;
            }
            else {
                searchCondition.order = '';
                searchCondition.isAsc = false;
            }
        }
        doSearch();
    });
}

function bindSearchCondition() {
    $("#searchCondition div[field],#searchCondition ul[field]").each(function () {
        var fieldValue = searchCondition[$(this).attr("field")];
        if (fieldValue) {
            // change style
            $(this).find("a").removeClass("fco").addClass("fcbl");
            $(this).find("a").removeClass("fwb");
            $(this).find("a[data=" + fieldValue + "]").addClass("fco").addClass("fwb");
        }
    });
    // 设置片区显示
    if (searchCondition.district > 0) {
        $("#zone").show();
        $("#zone li").hide();
        $("#zone li[district=" + searchCondition.district + "]").show();
    }
    //设置片区勾选
    if (searchCondition.zone) {
        var zones = searchCondition.zone.split(',');
        $("#zone input[type=checkbox]").each(function () {
            for (var i = 0; i < zones.length; i++) {
                this.checked = $(this).attr("zoneId") == zones[i];
                if (this.checked) {
                    var label = $("#zone label[for=" + $(this).attr("id") + "]");
                    label.addClass("fco").addClass("fwb");
                    // 已经找到并设置值，退出循环
                    break;
                }
            }
        });
    }

    var fitmentType = searchCondition["fitmentType"];
    // 绑定装修类型
    if (fitmentType) {
        $("#fitment input[type=checkbox]").each(function () {
            this.checked = fitmentType.indexOf($(this).attr("data")) > -1;
            var label = $("#fitment label[for=" + $(this).attr("id") + "]");
            if (this.checked) {
                label.addClass("fco").addClass("fwb");
            }
        });
        $("#fitment a").removeClass("fco").removeClass("fwb").addClass("fcbl");
    }

    // 多图、新推、详述checkbox
    $("#HasPicture, #IsNew, #IsDetail").change(function () {
        doSearch();
    });
}


function selectDistrict() {
    var district = $("#districtSelect").val();
    if (!district)
        district = 0;

    /*$("input[type=radio][district]").hide();
    $("label[district]").hide();
    $("input[type=radio][district=" + district + "]").show();
    $("label[district=" + district + "]").show();*/

    $("input[type=radio][district]").parent(".zoneBox").hide();
    $("input[type=radio][district=" + district + "]").parent(".zoneBox").show();
}


var lastAutoMatch = '';
var lastAutoMatchFuntion = null;
// 初始化自动楼盘匹配
function initProjectAutoMatch() {
    $("#projectTitle").keyup(function () {
        clearTimeout(lastAutoMatchFuntion);
        lastAutoMatchFuntion = setTimeout(function () {
            var title = $.trim($("#projectTitle").val());
            if (title && title != lastAutoMatch) {
                lastAutoMatch = title;
                $.ajax({
                    type: 'POST',
                    url: '/project/FindProjectsByName?title=' + escape(title),
                    dataType: "json",
                    cache: false,
                    success: function (data) {
                        //alert(data);
                        $("#guessProject").hide();
                        if (data && data.length > 0) {
                            $("#projectCondidates").text('');
                            $("#guessProject").fadeIn();
                            for (var i = 0; i < data.length; i++) {
                                appendProjectCondidate(data[i]);
                            }
                        }
                    },
                    error: ajaxError
                });
            }
        }, 1000);
    });
}

// 添加匹配的候选楼盘
function appendProjectCondidate(project) {
    var html = "<a href='javascript:void(0)' class='fcbl prm' zoneId='" + project.ZoneId + "' proejctId='" + project.Id + "'>" + project.Title + "</a> ";
    $("#projectCondidates").append(html);
    $("#projectCondidates a").bind("click", function () {
        $("#projectTitle").val($(this).text());
        var zoneRadio = $("input[type=radio]#zone" + $(this).attr("zoneId"))
        zoneRadio.attr("checked", "checked");

        $("#districtSelect").val(zoneRadio.attr("district"));
        selectDistrict();
        // 选择完毕之后隐藏
        setTimeout(function () { $("#guessProject").fadeOut(1000); }, 5000);
    });
}

function initPublishTypeTab() {
    $("a[publishType]").click(function () {
        if (searchCondition.publishType != $(this).attr("publishType")) {
            searchCondition.publishType = $(this).attr("publishType");
            doSearch();
        }
    });
}

function initColspanFun() {
    $("#colspanFun").find("span").bind('click', function () {
        $("#MoreFunction").slideToggle();
        if ($(this).text() == constants.moreFunctionExpand) {
            $(this).text(constants.moreFunctionCollapsed);
            $(this).removeClass("arrowBtn").addClass("arrowBtnTop");
            searchCondition.more = true;
        }
        else {
            $(this).text(constants.moreFunctionExpand);
            $(this).removeClass("arrowBtnTop").addClass("arrowBtn");
            searchCondition.more = false;
        }
    });
}

function initFavBtn() {
    $.ajax({
        type: 'POST',
        url: '/SaleInfoFav/MyFavIds',
        dataType: "json",
        cache: false,
        success: function (data) {
            if (data.length > 0) {
                $("a.favBtn").each(function () {
                    for (var i = 0; i < data.length; i++) {
                        if ($(this).attr("saleInfoId") == data[i]) {
                            $(this).addClass("favBtnDone");
                        }
                        else {
                            $(this).click(function () {
                                if (!$(this).hasClass("favBtnDone")) {
                                    DoPost('/SaleInfoFav/AddFav?saleInfoId=' + $(this).attr("saleInfoId"));
                                    $(this).addClass("favBtnDone");
                                }
                                return false;
                            });
                        }
                    }
                });
            }
            else {
                $("a.favBtn").click(function () {
                    if (!$(this).hasClass("favBtnDone")) {
                        DoPost('/SaleInfoFav/AddFav?saleInfoId=' + $(this).attr("saleInfoId"));
                        $(this).addClass("favBtnDone");
                    }
                    return false;
                });
            }
        },
        error: ajaxError
    });
}


// 修正数字输入
function fixNumber(elem) {
    $(elem).parent().find("input[type=text]").each(function () {
        if ($(this).attr("id") == "projectTitle")
            return
        var val = parseInt($(this).val());
        if (!val || val < 0)
            $(this).val('');
        else
            $(this).val(val);

    });

    var inputMin = $(elem).parent().find("input.min");
    var inputMax = $(elem).parent().find("input.max");

    if (inputMin.length > 0 && inputMax.length > 0) {
        var valMin = parseInt(inputMin.val());
        var valMax = parseInt(inputMax.val());

        if (valMin > 0 && valMax > 0 && valMax < valMin) {
            // 当最大值小于最小值时，交换
            inputMax.val(valMin);
            inputMin.val(valMax);
        }
    }

}

function calculateCommonCondition(elem) { // elem 是确定按钮
    var field = $(elem).attr("field");
    var data = '';
    var inputs = $(elem).parent().find("input[type=text]");
    var hasValue = false;
    inputs.each(function () {
        var val = $(this).val();
        if (val == '') {
            val = 0;
        }
        else {
            hasValue = true;
        }
        data = data + val + "-";
    });

    if (hasValue && data.length > 0) {
        data = data.substring(0, data.length - 1);
        searchCondition[field] = data;
    }
    else {
        searchCondition[field] = '';
    }
}
function calculateLocationCondition() {
    var projectInput = $("#projectTitle");
    if (projectInput.val() != projectInput.attr("defaultText")) {
        // 有楼盘显示楼盘信息
        searchCondition.project = projectInput.val();
    }
    else {
        searchCondition.project = '';
    }

    // 片区
    var zoneIds = '';
    var zoneTitles = '';
    $("#zone input[type=checkbox]").each(function () {
        if (this.checked) {
            zoneIds += $(this).attr("zoneId") + ",";
            zoneTitles += $(this).attr("zoneTitle") + ",";
        }
    });
    if (zoneIds) {
        zoneIds = zoneIds.substring(0, zoneIds.length - 1);
        zoneTitles = zoneTitles.substring(0, zoneTitles.length - 1);
    }
    searchCondition.zone = zoneIds;
    searchCondition.zoneName = zoneTitles;

    searchCondition.district = $("#district a.fco").attr("data");
    searchCondition.districtName = $("#district a.fco").text();
}

function calculateFitmentTypeCondition() {
    var data = '';
    $("#fitment input[type=checkbox]").each(function () {
        if (this.checked)
            data += $(this).attr("data") + ",";
    });
    if (data) {
        data = data.substring(0, data.length - 1);
    }
    searchCondition['fitmentType'] = data;
}

function renewCurrentSearchCondition() {
    $("#currentCondition").html('');
    //if (searchCondition.district > 0 && searchCondition.districtName) {
    writeLocationCondition();
    //}
    if (searchCondition.houseType) {
        writeHouseTypeCondition();
    }
    if (searchCondition.price) {
        var unit = searchCondition.saleInfoType != 1 ? "万" : "元/月";
        writeCommonCondition('price', '价格', searchCondition.price, unit);
    }

    if (searchCondition.floor) {
        writeCommonCondition('floor', '楼层', searchCondition.floor, '层');
    }

    if (searchCondition.area) {
        writeCommonCondition('area', '面积', searchCondition.area, '平米');
    }

    if (searchCondition.year) {
        writeCommonCondition('year', '房龄', searchCondition.year, '年');
    }

    if (searchCondition.mobile) {
        setCurrentCondition('mobile', '手机', searchCondition.mobile);
    }

    if (searchCondition.fitmentType) {
        writeFitmentTypeCondition();
    }
}

function writeCommonCondition(field, title, value, unit) {
    var name = "";
    var array = value.split("-");
    if (array.length != 2 || (array[0] == '0' && array[1] == '0')) {
        return;
    }

    if (array[0] == '0') {
        name = array[1] + unit + "以下";
    }
    else if (array[1] == '0') {
        name = array[0] + unit + "以上";
    }
    else {
        name = value + unit;
    }
    setCurrentCondition(field, title, name);
}

function writeLocationCondition() {
    if (searchCondition.zone) {
        // 没有楼盘有片区，显示片区信息
        setCurrentCondition("zone", "位置", searchCondition.zoneName);
    }
    else if (searchCondition.district) {
        setCurrentCondition("district", "位置", searchCondition.districtName);
    }
    if (searchCondition.project) {
        // 有楼盘显示楼盘信息
        setCurrentCondition("project", "位置", searchCondition.project);
    }
}

function writeHouseTypeCondition() {
    var array = searchCondition.houseType.split("-");
    var name = '';
    if (array.length == 3) {
        if (array[0] != '0')
            name += array[0] + "房";
        if (array[1] != '0')
            name += array[1] + "厅";
        if (array[2] != '0')
            name += array[2] + "卫";
        //        if (array[3] != '0')
        //            name += array[3] + "阳台";
        if (name)
            setCurrentCondition("houseType", "户型", name);
    }
}

function writeFitmentTypeCondition() {
    if (searchCondition.fitmentType) {
        var name = '';
        if (searchCondition.fitmentType.indexOf('0') > -1) {
            name += '毛坯,';
        }
        if (searchCondition.fitmentType.indexOf('1') > -1) {
            name += '普装,';
        }
        if (searchCondition.fitmentType.indexOf('2') > -1) {
            name += '中装,';
        }
        if (searchCondition.fitmentType.indexOf('3') > -1) {
            name += '高装,';
        }
        if (searchCondition.fitmentType.indexOf('99') > -1) {
            name += '其他,';
        }
        if (name) {
            name = name.substring(0, name.length - 1);
            setCurrentCondition("fitmentType", "装修", name);
        }
    }
}

function setCurrentCondition(field, title, name) {
    $("#currentCondition").append('<b>' + title + '：</b><a field="' + field + '" title="移除此条件" class="closeBtnBlue fco mrm" href="#">' + name + '</a>');
    bindCurrentConditionButton();
}

function bindCurrentConditionButton() {
    $("#currentCondition a.closeBtnBlue").bind("click", function () {
        var field = $(this).attr('field');
        if (field) {
            searchCondition[field] = '';
            if (field == 'zone') {
                searchCondition['district'] = ''; // 移除片区同时移除区域
            }
            renewCurrentSearchCondition();
            doSearch();
        }
        return false;
    });
}

function doSearch() {
    var url = "/?r=search";
    if (searchCondition.saleInfoType > 0) {
        url += "&saleInfoType=" + searchCondition.saleInfoType;
    }
    if (searchCondition.district) {
        url += "&district=" + searchCondition.district;
        url += "&districtName=" + escape(searchCondition.districtName);
    }
    if (searchCondition.zone) {
        url += "&zone=" + searchCondition.zone;
        url += "&zoneName=" + escape(searchCondition.zoneName);
    }

    if (searchCondition.project) {
        url += "&project=" + escape(searchCondition.project);
    }
    if (searchCondition.houseType) {
        url += "&houseType=" + searchCondition.houseType;
    }
    if (searchCondition.price) {
        url += "&price=" + searchCondition.price;
    }
    if (searchCondition.floor) {
        url += "&floor=" + searchCondition.floor;
    }
    if (searchCondition.fitmentType) {
        url += "&fitmentType=" + searchCondition.fitmentType;
    }
    if (searchCondition.area) {
        url += "&area=" + searchCondition.area;
    }
    if (searchCondition.year) {
        url += "&year=" + searchCondition.year;
    }
    if (searchCondition.searchType) {
        url += "&searchType=" + searchCondition.searchType;
    }
    if (searchCondition.publishType && searchCondition.publishType > 0) {
        url += "&publishType=" + searchCondition.publishType;
    }
    if (searchCondition.page) {
        url += "&page=" + searchCondition.page;
    }
    if (searchCondition.more) {
        url += "&more=" + searchCondition.more;
    }
    if (searchCondition.order) {
        url += "&order=" + searchCondition.order;
    }
    if ($("#HasPicture").attr("checked")) {
        url += "&hasPicture=true";
    }
    if ($("#IsNew").attr("checked")) {
        url += "&IsNew=true";
    }
    if ($("#IsDetail").attr("checked")) {
        url += "&IsDetail=true";
    }
    if (searchCondition.mobile) {
        url += "&mobile=" + searchCondition.mobile;
    }
    if (searchCondition.isAsc) {
        url += "&isAsc=" + searchCondition.isAsc;
    }

    window.location.href = url;
}


function SetMap() {
    initialize($("#Latitude").val(), $("#Longitude").val(), true);
}

function slideImages() {
    $('#houseImage').slides({
        generateNextPrev: true,
        play: 0
    });
    $('#estateImage').slides({
        generateNextPrev: true,
        play: 0
    });
}

function bindForm() {
    $("form").each(function () {
        var eventName = "blur";
        if ($.browser.msie) {
            eventName = "focusout";
        }

        $(this).find("input.required").bind(eventName, function () {
            validateInput(this);
        });
    });

    $("form").bind("submit", function () {
        var success = true;
        $(this).find("input.required").each(function () {
            success = validateInput(this) && success;
        });
        if (!success) {
            var alertMessage = $(this).attr("alertMessage");
            alert(alertMessage);
        }
        return success;
    });

}

function validateInput(element) {
    var messageSpan = $("span[targetId='" + $(element).attr("id") + "']");
    messageSpan.removeClass("errorMsg");
    messageSpan.removeClass("notification");

    var success = false;
    if ($(element).hasClass("required")) {
        success = !!$(element).val();
    }
    if ($(element).hasClass("char")) { // 字母、数字、汉字等普通字符的组合
        success = success && isCharCn($(element).val());
    }
    if ($(element).hasClass("number")) {
        var number = parseInt($(element).val());
        success = success && !isNaN(number);
        if ($(element).attr("max")) {
            success = success && number <= parseInt($(element).attr("max"));
        }
        if ($(element).attr("min")) {
            success = success && number >= parseInt($(element).attr("min"));
        }
    }
    if ($(element).hasClass("email")) {
        success = success && isEmail($(element).val());
    }
    if ($(element).hasClass("mobile")) {
        success = success && isMobile($(element).val());
    }
    if ($(element).hasClass("length")) {
        success = success && $(element).val().length >= parseInt($(element).attr("minlength"));
    }

    if ($(element).attr("id") == "ConfirmPassword") {
        success = success && $(element).val() == $("#Password").val();
    }

    if (!success) {
        messageSpan.show();
        messageSpan.addClass("errorMsg");

        return false;
    }
    else {
        messageSpan.addClass("notification");
        messageSpan.fadeOut();
        return true;
    }
}

function AddAutoRefreshTime(userIdAppendix) {
    if (!userIdAppendix) {
        userIdAppendix = "?";
    }
    else {
        userIdAppendix += "&";
    }
    if ($("#StartTime").val() && $("#EndTime").val()) {
        DoPost("/AutoRefreshTime/Add" + userIdAppendix + "StartTime=" + $("#StartTime").val() + "&EndTime=" + $("#EndTime").val());
    }
    else {
        alert("请选择开始时间和结束时间！");
    }
}

function ajaxFileUpload() {
    $("#loading")
		.ajaxStart(function () {
		    $(this).show();
		})
		.ajaxComplete(function () {
		    $(this).hide();
		});

    $.ajaxFileUpload
		(
			{
			    url: 'doajaxfileupload.php',
			    secureuri: false,
			    fileElementId: 'fileToUpload',
			    dataType: 'json',
			    data: { name: 'logan', id: 'id' },
			    success: function (data, status) {
			        if (typeof (data.error) != 'undefined') {
			            if (data.error != '') {
			                alert(data.error);
			            } else {
			                alert(data.msg);
			            }
			        }
			    },
			    error: function (data, status, e) {
			        alert(e);
			    }
			}
		)

    return false;

}

function AddImage(filename, picId, type) {
    //    console.debug(filename);
    //    console.debug(picId);
    //    console.debug(type);
    var inputName = "SaleInfoPictures";
    if (type == 1) {
        inputName = "ProjectPictures";
    }
    var picture = $("#pictureTemplate" + type).clone();
    picture.find("input[type=hidden]").val(picId).attr("name", inputName);
    picture.find("img").attr("src", "/images/upload/" + filename);
    picture.removeClass("hidden").attr("id", "");
    picture.find("a.delBtn").click(function () {
        if ($(this).attr('picType') == '0') {
            count0 = count0 - 1;
            renewPictureTip();
        }
        else if ($(this).attr('picType') == '1') {
            count1 = count1 - 1;
        }
        $(this).parent().parent().fadeOut(function () {
            $(this).remove();
        });
    });
    picture.find("a[PostUrl]").each(function () {
        $(this).attr("PostUrl", $(this).attr("PostUrl").replace("$PictureId$", picId));
    });
    // 绑定post事件
    picture.find("a[PostUrl]").click(function () {
        if ($(this).attr("ConfirmMessage") && !confirm($(this).attr("ConfirmMessage"))) {
            return;
        }
        DoPost($(this).attr("postUrl"));
    });
    // 绑定图片移动事件
    picture.find("a.setNext").click(function () {
        picture.insertAfter(picture.next().not(".clear"));
        // renewMainPicture(picture.parent());

    });
    picture.find("a.setPre").click(function () {
        picture.insertBefore(picture.prev());
        // renewMainPicture(picture.parent());
    });

    picture.insertBefore($("#pictureContainer" + type).find("li.clear"));
    parent.fixFrame(parent.document.getElementById('frame'));
}

function bindImageDelBtn() {
    $("a.delBtn").click(function () {
        if ($(this).attr('picType') == '0') {
            count0 = count0 - 1;
            renewPictureTip();
        }
        else if ($(this).attr('picType') == '1') {
            count1 = count1 - 1;
        }
        $(this).parent().parent().fadeOut(function () {
            $(this).remove();
        });
    });


}

function bindPictureContainer() {
    var picture = $("#pictureContainer0,#pictureContainer1").children();
    // 绑定图片移动事件
    picture.find("a.setNext").click(function () {
        var picCell = $(this).parent().parent();
        picCell.insertAfter(picCell.next().not(".clear"));
        // renewMainPicture(picture.parent());

    });
    picture.find("a.setPre").click(function () {
        var picCell = $(this).parent().parent();
        picCell.insertBefore(picCell.prev());
        // renewMainPicture(picture.parent());
    });
}

// 更新标题图样式
function renewMainPicture(pictureContainer) {
    pictureContainer.find("div.mainPicture").removeClass("mainPicture");
    pictureContainer.find("div.uplpadImgBox").first().addClass("mainPicture");

}

function ChangeImgCode() {
    var randomnum = Math.random();
    var getimagecode = document.getElementById("ImgVerifyCode");
    getimagecode.src = "/Home/RandomImage?r=" + randomnum;
}

function checkUserExists(username) {
    if (username && username.length >= 6) {
        $.ajax({
            beforeSend: function (XMLHttpRequest) {
                XMLHttpRequest.setRequestHeader("ajax", "true");
            },
            type: 'POST',
            url: "/User/IsExists?username=" + username,
            dataType: "json",
            cache: false,
            success: function (data) {
                if (data.message) {
                    if (confirm(data.message)) {
                        window.location.href = '/Home/FindPassword?u=' + username;
                    }
                    else {
                        alert("该用户名已注册！请使用其他用户名！");
                    }
                }
            },
            error: ajaxError
        });
    }
}


function checkMobileExists(mobile) {
    if (mobile && mobile.length >= 6)
        DoPost("/User/IsMobileExists?mobile=" + mobile);
}

function bindComplaint() {
    $("a[ComplaintType]").click(function () {
        if (confirm("确认要投诉该房源吗？")) {
            var complaintType = $(this).attr("ComplaintType");
            var url = "/Complaint/Submit?type=" + complaintType + "&saleInfoId=" + $(this).attr("saleInfoId");
            if (complaintType == "99") {
                if ($("#ComplaintContent").val()) {
                    url = url + "&content=" + $("#ComplaintContent").val();
                }
                else {
                    alert("请填写投诉内容！");
                    $("#ComplaintContent").focus();
                    return;
                }
            }
            DoPost(url);
        }
    });
}

function initCorrectMap() {

    $("#CorrectMap").show(800);
    setTimeout(function () {
        initialize($("#Latitude").val(), $("#Longitude").val(), true, "map_canvas2");
    }, 1000);
}

function SubmitCorrectMap() {
    if (!$("#Latitude").val() || !$("#Longitude").val()) {
        alert("请标注地图！");
    }
    else {
        DoPost("/Project/Correct/?CorrectType=0&CorrectProjectId=" + $("#CorrectProjectId").val() + "&Latitude=" + $("#Latitude").val() + "&Longitude=" + $("#Longitude").val());
    }
}
function initCorrectInfo() {
    $('#CorrectInfo').show(800);
    bindForm();
}

var kCount = 0;
function validateKCount() {
    if (kCount > 500) {
        alert('房源说明不能够超过500字！');
        return false;
    }
}

function changeMenu(url) {
    if (url) {
        $(parent.document).find("[url]").removeClass("selected");
        parent.gotoFrame(url);
        $(parent.document).find("a[url='" + url.split('?')[0] + "']").addClass("selected");
    }
    return false;
    //    console.debug($(parent.document).find("a[url='" + url + "']"));
    //    $(parent.document).find("a[url='" + url + "']").click();
}

function renewPictureTip() {
    if (count0 > 0) {
        $("#picTip0").hide();
        $("#picTip1").show();
    }
    else {
        $("#picTip0").show();
        $("#picTip1").hide();
    }
}

function refreshUploadUser(elem) {
    if (elem && elem.length > 0) {
        var userDiv = $("#user" + elem.attr("userid"));
        var userName = userDiv.attr("username");
        var mobile = userDiv.attr("mobile");
        if (!userName) {
            userName = "游客";
        }
        if (!mobile) {
            mobile = "";
        }
        $("#uploadUserSpan").text(userName);
        $("#uploadUserSpan").attr("href", "/?r=v&mobile=" + mobile + "&saleInfoType=" + $("#uploadInfoSpan").attr("saleInfoType"));
    }
}

//小弹窗
function initSmallHopup() {
    if ($(".smallHopup").length > 0) {
        $(".smallHopupContainer").delay(6000).animate({
            opacity: 'show'
        }, 500);
        $(".smallHopupContainer").delay(16000).animate({
            opacity: 'hide'
        }, 500); 
    }
}
function closeSmallHopup(obj) {
    $(obj).parents(".smallHopupContainer").hide();
}

//切换城市
function initChangeCity() {
    if ($(".changeCity").length > 0) {
        $("#changeCityLink").bind("mouseenter", function () {
            $(".cityList").show();
        });
        $(".cityList").bind("mouseleave", function () {
            $(".cityList").hide();
        });
        $(".changeCity").bind("mouseleave", function () {
            $(".cityList").hide();
        });
        $(".cityList").find("a").bind("click", function () {
            changeCity(this);
        });
        $("a.city").bind("click", function () {
            changeCity(this);
        });
    }
}

function changeCity(elem) {
    if ($(elem).attr("cityId")) {
        // 设置cookie过期时间
        var date = new Date();
        var expireDays = 999;
        date.setTime(date.getTime() + expireDays * 24 * 3600 * 1000);
        document.cookie = "efecity=" + $(elem).attr("cityId") + ";path=/;expires=" + date.toGMTString();
        if (location.href.toLowerCase().indexOf('/home/myefe') > 0) {
            // 重新载入页面
            window.location.reload();
        }
        else {
            window.location.href = "/";
        }
    }
}